package org.budo.dubbo.protocol.http.dispatcher.websocket;

import javax.websocket.CloseReason;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;

import org.budo.dubbo.protocol.http.dispatcher.BudoHttpDispatcherUtil;
import org.budo.dubbo.protocol.http.invocation.adapter.ProtocolRequestHolder;
import org.budo.dubbo.protocol.http.invocation.adapter.ProtocolResponse;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class BudoHttpWebSocketServerEndpoint extends Endpoint implements MessageHandler.Whole<String> {
    private Session websocketSession;

    // 每一个 session 一个 BudoHttpWebSocketServerEndpoint 实例
    public BudoHttpWebSocketServerEndpoint() {
        log.debug("#18 this={}", this);
    }

    @Override
    public void onOpen(Session websocketSession, EndpointConfig config) {
        log.info("#18 onOpen, websocketSession=" + websocketSession + ", config=" + config);

        websocketSession.addMessageHandler(this); // 消息注册处理
        this.websocketSession = websocketSession;
    }

    @Override
    public void onClose(Session session, CloseReason closeReason) {
        log.info("#23 onClose, session=" + session + ", closeReason=" + closeReason);
    }

    @Override
    public void onError(Session session, Throwable throwable) {
        log.info("#28 onError, session=" + session + ", throwable=" + throwable);
    }

    // 消息处理
    @Override
    public void onMessage(String message) {
        log.debug("#39 onMessage, message={}, websocketSession={}, this={}", message, this.websocketSession, this);

        WebSocketProtocolRequest protocolRequest = new WebSocketProtocolRequest(message);
        ProtocolResponse protocolResponse = new WebSocketProtocolResponse(this.websocketSession);

        ProtocolRequestHolder.setThreadLocal(protocolRequest, protocolResponse);

        // 处理
        BudoHttpDispatcherUtil.onMessage(protocolRequest, protocolResponse);

        ProtocolRequestHolder.removeThreadLocal();
    }
}